<?php

class URIPattern
{
	// Required
	private $regex;
	
	// Optional
	private $view;
	private $name;
	private $params;
	
	// List of URIs this instance has matched, and the arguments they matched
	// with; this can be used to easily get the args back without rerunning
	// regex, slowly
	private $matches;
	
	public function __construct(array $args)
	{
		$this->regex = $args['uri'];
		
		// TODO: Make 'controller' key inhereted to subrouter patterns
		$this->controller = $args['controller']?:NULL;
		$this->view = $args['view']?:NULL;
		$this->name = $args['name']?:NULL;
		$this->params = $args['params']?:array();
		
		$this->matches = array();
	}
	
	public function matches($uri)
	{
		$count = preg_match('%'.$this->regex.'%', $uri, $matches);
		if ($count > 0)
		{
			$this->matches[$uri] = $this->form_arg_list($matches,
				$this->params);
			return $matches[0];
		}
		return false;
	}
	
	public function match_args($uri)
	{
		if (array_key_exists($uri, $this->matches))
		{
			return $this->matches[$uri];
		}
		else
		{
			return NULL;
		}
	}
	
	private function form_arg_list($match_args, $given_args)
	{
		$args = array();
		foreach ($match_args as $key => $value)
			if (!is_int($key)) $args[$key] = $value;
		return array_merge($args, $given_args);
	}
	
	/* Accessors */
	public function get_controller()
	{
		return $this->controller;
	}
	
	public function get_view()
	{
		return $this->view;
	}
	
	public function get_name()
	{
		return $this->name;
	}
	
	public function get_params()
	{
		return $this->params;
	}
}

?>